package command;

import server.KVMessage.StatusType;
import util.IKeyValueStorage;

public class CommandPut implements ICommand {
	private IKeyValueStorage storage;
	private String key;
	private String value;
	
	public CommandPut(IKeyValueStorage storage, String key, String value) {
		this.key = key;
		this.value = value;
		this.storage = storage;
	}
	
	@Override
	public String execute() {
		if (key==null || key.length()==0) {
			return ClientInputHandler.composeClientResponse(StatusType.PUT_ERROR, "ERROR: a key may not be null or empty", "");
		}
		boolean keyExisted = storage.containsKey(key);
		StatusType status = keyExisted ? StatusType.PUT_UPDATE : StatusType.PUT_SUCCESS;
		storage.put(key, value);
		return ClientInputHandler.composeClientResponse(status, key, value);
	}
}
